package com.cysion.study.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.PMoneyAdapter
import com.cysion.study.entity.AddressInfoPO
import com.cysion.study.entity.PbalanceDetailsListEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.base.ITEM_CLICK
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.activity_pmoney.*

class PMoneyActivity : BaseActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_pmoney

    override fun initView() {
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("我的钱包")
            setRightImg(R.mipmap.icon_course_detail_r)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                } else if (pos == TopBar.Pos.RIGHT) {
                    UIHelper.jump(self, PBindCardActivity::class.java)
                }
            }
        }

        tv_perfect.setOnClickListener(this)
        tv_submit.setOnClickListener(this)
        tv_select.setOnClickListener(this)

        initRecyclerView()
        initRefreshLayout()


    }

    private lateinit var mAdapter: PMoneyAdapter
    private val dataList: MutableList<PbalanceDetailsListEntity> = mutableListOf()
    private var curPage = 1


    override fun initData() {
        super.initData()
        smartLayout.autoRefresh()
    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setOnRefreshListener {
            curPage = 1
            getDataList()
            smartLayout.setEnableLoadMore(true)

        }
        smartLayout.setOnLoadMoreListener {
            getDataList()
        }
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        mAdapter = PMoneyAdapter(dataList, Box.context)
        rv_list.adapter = mAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        mAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == ITEM_CLICK) {//
                //type":余额类型  .充值 1.提现 2.提现退款 3.购买市集课程 4.托管缴费 5.家教订单 6.商城订单
                // 7.待定 8.活动订单 9.待定 10.家教订单拒绝退款(弃用) 11.家教报酬(弃用) 12.课程分销收益
                // 13、机构消课程后的收益 14、机构消活动后的收益  15、机构消研学后的收益  16、机构托管缴费收益
                // 17.机构提现余额减少  18.机构提现被拒绝，余额退回 19、机构托管续费收益
                // 20、家教老师消课收益 21、家教订单退款 22、家教老师待授课金额
                if (obj.type == "1") {
                    //提现详情
                    var bundle = Bundle()
                    bundle.putString("id", obj.id)
                    UIHelper.jump(this, PWithdrawDetailActivity::class.java, bundle)
                } else if (obj.type == "5") {
                    //购买详情
                    var bundle = Bundle()
                    bundle.putString("id", obj.id)
                    UIHelper.jump(this, PTeacherBuyDetailActivity::class.java, bundle)
                }else if (obj.type == "20") {
                    //消课详情
                    var bundle = Bundle()
                    bundle.putString("id", obj.id)
                    UIHelper.jump(this, PCancelCourseDetailActivity::class.java, bundle)
                }else if (obj.type == "21") {
                    //退款详情
                    var bundle = Bundle()
                    bundle.putString("id", obj.id)
                    UIHelper.jump(this, PBackMoneDetailActivity::class.java, bundle)
                }
                /* var bundle = Bundle()
                 bundle.putString("id",obj.id)//
                 bundle.putString("cid",obj.cid)//
                 bundle.putString("activityName",activityName)//
                 //活动详情
                 UIHelper.jump(this,ActivityDetailActivity::class.java,bundle)*/
//                UIHelper.jump(this, PCourseDetailActivity::class.java)

            }
        }
        //模拟数据
        /*if (mAdapter.itemCount == 0) {
            var lists: MutableList<String> = mutableListOf("","")
            dataList.addAll(lists)
            mAdapter.notifyDataSetChanged()
        }*/
    }

    private var timeType = "5"
    private fun getDataList() {
//        Alert.loading(context)
        stopRefresh()
        ApiClient.api.balanceDetails(UserCache.token, timeType, curPage.toString(), "10")
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    if (curPage == 1) {
                        dataList.clear()
                        if (it.size == 0) {
                            multiView.showEmpty()
                        }
                    }
                    if (it.size <= 0) {
                        smartLayout.setEnableLoadMore(false)
                    } else {
                        curPage++
                        dataList.addAll(it)
                        mAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }


    override fun onResume() {
        super.onResume()
        getUserInfos()
    }

    private fun getUserInfos() {
        ApiClient.api.getUserInfos(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    if (!TextUtils.isEmpty(it.id)) {
                        UserCache.save(it)
//                        tv_money.text = "￥ "+UserCache.userInfo?.money.toString()
//                        tv_money.text = "￥ "+it.money
                        //家教是否绑定银行卡：0、代表未绑定；1、代表已绑定
                        if (it.ifBindCard == "0") {
                            ll_bind.visibility = View.VISIBLE
                            tv_submit.text = "绑定"
                        } else {
                            tv_submit.text = "提现"
                            ll_bind.visibility = View.GONE
                        }
                        tv_wait.text = it.feduCrsMoney
                        tv_waitMoney.text = it.feduMoney
                        tv_allMoney.text = it.feduOverWithMoney
                    }
                }
            }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_select -> {
                val items = mutableListOf<AddressInfoPO>()
                //时间类型：1、近7天；2、近1个月；3、近3个月；4、近1年；5或者不填代表所有
                var item1 = AddressInfoPO("1", "近7天")
                var item2 = AddressInfoPO("2", "近1个月")
                var item3 = AddressInfoPO("3", "近3个月")
                var item4 = AddressInfoPO("4", "近1年")
                var item5 = AddressInfoPO("5", "所有")
                items.add(item1)
                items.add(item2)
                items.add(item3)
                items.add(item4)
                items.add(item5)

                //条件选择器
                val pvOptions = OptionsPickerBuilder(self,
                    OnOptionsSelectListener { options1, option2, options3, v ->
                        //返回选中位置
                        timeType = items[options1].id
                        tv_select.text = items[options1].name//山东省AddressInfoPO(id=2, name=济南2)章丘
                        smartLayout.autoRefresh()
                    }).setTitleText("选择时间范围").build<AddressInfoPO>()
                pvOptions.setPicker(items)
                pvOptions.show()

            }
            R.id.tv_perfect -> {//绑定
                UIHelper.jump(this, PBindCardActivity::class.java)
            }
            R.id.tv_submit -> {//提现
                if (tv_submit.text.toString() == "绑定") {
                    UIHelper.jump(this, PBindCardActivity::class.java)
                } else if (tv_submit.text.toString() == "提现") {
                    UIHelper.jump(this, PWithdrawActivity::class.java)
                }
            }

        }
    }

    override fun closeMvp() {
    }

}
